<?

//Initiate Authenticate
//SecurityRedirect ();
//error_reporting(E_ALL);

//initiate Vars
define("PRIMARY_KEY","nobkt");
$PRIMARY_KEY    = PRIMARY_KEY;
$PRIMARY_VALUE  = GetParam($PRIMARY_KEY,"");
$FileName       = "ais_transaction_dn.php";
$FileTemplate   = "ais_transaction_dn_form.html";
$SubHeaderTitle = "Transaction Account Receivable - Debit Note";
$TableName                  = "ais_memorial";
$HTMLFormName   = "DNSummaryForm";
$MaxGrid        = "100";
$KTRASL                = GetOfficeID();
//$HTMLFormName2  = "BudgetForm";

$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode         = "";

//Initiate Grid Fields;
$FormFields    = array("memorial_id"=>"","uraian"=>"","noref"=>"0","noorder"=>"","urut"=>"","dk"=>"","skada"=>"","jumlah"=>"number","uraian_a"=>"","uraian_b"=>"","uraian_c"=>"","uraian_d"=>"","kdact"=>"");

//buildsqlfield ("$TableName", $FormFields);

//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name",1);
$FormCValue    = BuildHTMLField($FormFields,"value",1);

//************ FORM ACTION **************
if (trim(GetParam("form",""))==trim($HTMLFormName)) {
        if (GetParam("FormAction","")=="Save") {
                list($day,$month,$year) = explode("/",GetParam("tglbkt",""));
                $tglbkt  = "$year-$month-$day";
                 list($day,$month,$year) = explode("/",GetParam("tglvat",""));
                $tglvat  = "$year-$month-$day";
                $crterm         = $DBConnection->dbc->get_var("SELECT top FROM tbldebtur WHERE CUCODE='".GetParam("debtur","")."' ");
                $duedate = date("Y-m-d",mktime(0, 0, 0, $month, $day+$crterm, $year));
//                print $crterm." ".$tglbkt." ".$duedate;die();
                $rate    = StrToNumber (GetParam("rate",""));

		$SQLvat = "SELECT rate FROM ais_kurspjk WHERE tglbkt <= '".$tglvat."' AND curr='".GetParam("curr","")."' ORDER BY tglbkt DESC LIMIT 1";
//                print $SQL; die();
                global $Ratevat;
                $Ratevat = $DBConnection->dbc->get_var($SQLvat);

                if (trim(GetParam("nobkt",""))=="AUTO NUMBERED BY SYSTEM")        {
                        $ObjNumber  = new autonumber(GetParam("tglbkt",""));
                        $TransNo = $ObjNumber->GetNumber("ND");
                        FormSave("ais_memorial", "uraian", $FormFields, array("debtur"=>GetParam("debtur",""),"debnam"=>GetParam("debnam",""), "principal"=>GetParam("principal",""),"principal_code"=>GetParam("principal_code",""),"ledger"=>GetPeriod(GetParam("tglbkt","")),"duedate"=>$duedate,"curr"=>GetParam("curr",""),"inc_ppn"=>GetParam("inc_ppn",""),"bkn"=>GetParam("bkn",""),"rate"=>$rate,"tglbkt"=>$tglbkt,"tglvat"=>$tglvat,"nobkt"=>$TransNo,
                        "ktrasl"=>GetOfficeID(),"kdbank"=>GetParam("kdbank",""),"typevat"=>GetParam("typevat",""),"vat"=>GetParam("vat",""),"vatrate"=>$Ratevat,"location"=>GetParam("location","")),"memorial_id");
                        $SQLYear = "SELECT ledger FROM tblcoa ORDER BY ledger DESC LIMIT 1";
                        $ledger =  $DBConnection->dbc->get_var($SQLYear);
                        $SQL = "
                                SELECT SUM(ais_memorial.jumlah)
                                FROM ais_memorial
                                INNER JOIN tblcoa ON ais_memorial.skada = tblcoa.skada AND tblcoa.inc_ppn=1 AND tblcoa.ledger=$ledger
                                WHERE nobkt='$TransNo'
                                ";
                                //print $SQL;
                        $PPNJumlah = $DBConnection->dbc->get_var($SQL);

                        if ($PPNJumlah>0) {
                                $DBConnection->AddData("urut","998");
                                $DBConnection->AddData("uraian","PPN 10%");
                                //$DBConnection->AddData("jumlah",$Jumlah*10/100);
                                $DBConnection->AddData("skada",GetPPNSkada());
                                $DBConnection->AddData("curr",GetParam("curr",""));
                                $DBConnection->AddData("rate",StrToNumber(GetParam("rate","")));
                                $DBConnection->AddData("inc_ppn",GetParam("inc_ppn",""));
                                $DBConnection->AddData("bkn",GetParam("bkn",""));
                                $DBConnection->AddData("jenis",1);
                                $DBConnection->AddData("dk",'K');
                                $DBConnection->AddData("typevat",GetParam("typevat",""));
                                $DBConnection->AddData("vat",GetParam("vat",""));
                                $DBConnection->AddData("vatrate",$Ratevat);
                                $DBConnection->AddData("location",GetParam("location",""));
                                $DBConnection->AddData("dol",StrToNumber(GetParam("total_ppn","")));
                                $DBConnection->AddData("jumlah",$PPNJumlah*10/100);
                                $DBConnection->AddData("rupiah",$PPNJumlah*StrToNumber(GetParam("rate",""))*10/100);
                                $DBConnection->AddData("kdact","ADM");
                                $DBConnection->AddData("ledger",GetPeriod(GetParam("tglbkt","")));
                                $DBConnection->AddData("debnam",GetParam("debnam",""));
                                $DBConnection->AddData("debtur",GetParam("debtur",""));
                                $DBConnection->AddData("principal",GetParam("principal",""));
                                $DBConnection->AddData("principal_code",GetParam("principal_code",""));
                                $DBConnection->AddData("nobkt",$TransNo);
                                $DBConnection->AddData("tglbkt",$tglbkt);
                                $DBConnection->AddData("tglvat",$tglvat);
                                $DBConnection->AddData("ktrasl",GetOfficeID());
                                $DBConnection->InsertData($TableName);
                        }
//                        $SQL = "SELECT SUM(ais_memorial.jumlah) FROM ais_memorial WHERE nobkt='$TransNo' AND skada <> '".GetPPNSkada()."%'";
                        $SQL = "SELECT SUM(ais_memorial.jumlah) FROM ais_memorial WHERE nobkt='$TransNo'";
                        $Jumlah = $DBConnection->dbc->get_var($SQL);

			$SQL = "SELECT SUM(ais_memorial.rupiah) FROM ais_memorial WHERE nobkt='$TransNo' and urut<>999";
                        $Rupiah = $DBConnection->dbc->get_var($SQL);

                        $DBConnection->add_data("ais_memorial","urut","999");
                        $DBConnection->add_data("ais_memorial","ktrasl",GetOfficeID());
                        $DBConnection->add_data("ais_memorial","kdbank",GetParam("kdbank",""));
                        $DBConnection->add_data("ais_memorial","ledger",GetPeriod(GetParam("tglbkt","")));
                        $DBConnection->add_data("ais_memorial","curr",GetParam("curr",""));
                        $DBConnection->add_data("ais_memorial","inc_ppn",GetParam("inc_ppn",""));
                        $DBConnection->add_data("ais_memorial","bkn",GetParam("bkn",""));
                        $DBConnection->add_data("ais_memorial","location",GetParam("location",""));
                        $DBConnection->add_data("ais_memorial","kdact",GetParam("kdact999",""));
                        $DBConnection->add_data("ais_memorial","rate",$rate);
                        $DBConnection->add_data("ais_memorial","typevat",GetParam("typevat",""));
                        $DBConnection->add_data("ais_memorial","vat",GetParam("vat",""));
                        $DBConnection->add_data("ais_memorial","nobkt",$TransNo);
                        $DBConnection->add_data("ais_memorial","tglbkt",$tglbkt);
                        $DBConnection->add_data("ais_memorial","tglvat",$tglvat);
                        $DBConnection->add_data("ais_memorial","vatrate",$Ratevat);
                        $DBConnection->add_data("ais_memorial","duedate",$duedate);
                        $DBConnection->add_data("ais_memorial","dk",GetParam("dk999",""));
                        $DBConnection->add_data("ais_memorial","noorder",GetParam("noorder999",""));
                        $DBConnection->add_data("ais_memorial","debtur",GetParam("debtur",""));
                        $DBConnection->add_data("ais_memorial","debnam",GetParam("debnam",""));
                        $DBConnection->add_data("ais_memorial","principal",GetParam("principal",""));
                        $DBConnection->add_data("ais_memorial","principal_code",GetParam("principal_code",""));
                        $DBConnection->add_data("ais_memorial","skada",GetParam("skada999",""));
                        $DBConnection->add_data("ais_memorial","uraian",GetParam("uraian999",""));
                        $DBConnection->add_data("ais_memorial","jumlah",$Jumlah);
                        //$DBConnection->add_data("ais_memorial","rupiah",($Jumlah) * $rate);
			$DBConnection->add_data("ais_memorial","rupiah",$Rupiah);


                        $DBConnection->add_data("ais_memorial","noref",StrToNumber(GetParam("noref1","")));

                        $DBConnection->InsertGrid();

//                        $DBConnection->dbc->debug();
                        SetLogActivity($TransNo,"Create","");
                        CreateNPWP($TransNo);

            } else {

                          $TransNo = GetParam("nobkt","");

                        $DBConnection->dbc->query("DELETE FROM ais_memorial WHERE ktrasl='".GetOfficeID()."' AND nobkt='".$TransNo."' ");
                        $DBConnection->dbc->query("DELETE FROM ais_piutang WHERE ktrasl='".GetOfficeID()."' AND nobkt='".$TransNo."' ");

                        FormSave("ais_memorial", "uraian", $FormFields, array("debtur"=>GetParam("debtur",""),"debnam"=>GetParam("debnam",""), "principal"=>GetParam("principal",""),"principal_code"=>GetParam("principal_code",""),"ledger"=>GetPeriod(GetParam("tglbkt","")),"duedate"=>$duedate,"curr"=>GetParam("curr",""),"inc_ppn"=>GetParam("inc_ppn",""),"bkn"=>GetParam("bkn",""),"rate"=>$rate,"tglbkt"=>$tglbkt,"tglvat"=>$tglvat,"nobkt"=>$TransNo,
                        "ktrasl"=>GetOfficeID(),"kdbank"=>GetParam("kdbank",""),"typevat"=>GetParam("typevat",""),"vat"=>GetParam("vat",""),"vatrate"=>$Ratevat,"location"=>GetParam("location","")),"memorial_id");
                        $SQL = "DELETE FROM $TableName WHERE skada like '".GetPPNSkada()."' AND nobkt = '$TransNo' ";
                        $DBConnection->dbc->query($SQL);

                        $SQLYear = "SELECT ledger FROM tblcoa ORDER BY ledger DESC LIMIT 1";
                        $ledger =  $DBConnection->dbc->get_var($SQLYear);

                        $SQL = "
                                SELECT SUM(ais_memorial.jumlah)
                                FROM ais_memorial
                                INNER JOIN tblcoa ON ais_memorial.skada = tblcoa.skada AND tblcoa.inc_ppn=1 AND tblcoa.ledger=$ledger
                                WHERE nobkt='$TransNo'
                                ";
                                //print $SQL;
                        $PPNJumlah = $DBConnection->dbc->get_var($SQL);
                        if ($PPNJumlah>0) {
                                $DBConnection->AddData("urut","998");
                                $DBConnection->AddData("uraian","PPN 10%");
                                //$DBConnection->AddData("jumlah",$Jumlah*10/100);
                                $DBConnection->AddData("skada",GetPPNSkada());
                                $DBConnection->AddData("curr",GetParam("curr",""));
                                $DBConnection->AddData("inc_ppn",GetParam("inc_ppn",""));
                                $DBConnection->AddData("rate",StrToNumber(GetParam("rate","")));

                                $DBConnection->AddData("jenis",1);
                                $DBConnection->AddData("dk",'K');
                                $DBConnection->AddData("typevat",GetParam("typevat",""));
                                $DBConnection->AddData("vat",GetParam("vat",""));
                                $DBConnection->AddData("kdact","ADM");
                                $DBConnection->AddData("location",GetParam("location",""));
                                $DBConnection->AddData("dol",StrToNumber(GetParam("total_ppn","")));
                                $DBConnection->AddData("jumlah",$PPNJumlah*10/100);
                                $DBConnection->AddData("rupiah",$PPNJumlah*StrToNumber(GetParam("rate",""))*10/100);
                                $DBConnection->AddData("ledger",GetPeriod(GetParam("tglbkt","")));
                                $DBConnection->AddData("debnam",GetParam("debnam",""));
                                $DBConnection->AddData("debtur",GetParam("debtur",""));
                                $DBConnection->AddData("principal",GetParam("principal",""));
                                $DBConnection->AddData("principal_code",GetParam("principal_code",""));
                                $DBConnection->AddData("nobkt",$TransNo);
                                $DBConnection->AddData("tglbkt",$tglbkt);
                        	$DBConnection->addData("vatrate",$Ratevat);
                                $DBConnection->AddData("tglvat",$tglvat);
                                $DBConnection->AddData("duedate",$duedate);
                                $DBConnection->AddData("ktrasl",GetOfficeID());
                                $DBConnection->AddData("bkn",GetParam("bkn",""));
                                $DBConnection->InsertData($TableName);
                        }
                        $SQL = "SELECT sum(jumlah) FROM ais_memorial WHERE nobkt='$TransNo'";
                        $Jumlah = $DBConnection->dbc->get_var($SQL);

						$SQL = "SELECT sum(rupiah) FROM ais_memorial WHERE nobkt='$TransNo' and urut<>999";
                        $Rupiah = $DBConnection->dbc->get_var($SQL);

                        $DBConnection->add_data("ais_memorial","urut","999");
                        $DBConnection->add_data("ais_memorial","ktrasl",GetOfficeID());
                        $DBConnection->add_data("ais_memorial","kdbank",GetParam("kdbank",""));
                        $DBConnection->add_data("ais_memorial","ledger",GetPeriod(GetParam("tglbkt","")));
                        $DBConnection->add_data("ais_memorial","curr",GetParam("curr",""));
                        $DBConnection->add_data("ais_memorial","inc_ppn",GetParam("inc_ppn",""));
                        $DBConnection->add_data("ais_memorial","location",GetParam("location",""));
                        $DBConnection->add_data("ais_memorial","rate",$rate);
                        $DBConnection->add_data("ais_memorial","nobkt",$TransNo);
                        $DBConnection->add_data("ais_memorial","tglbkt",$tglbkt);
                        $DBConnection->add_data("ais_memorial","tglvat",$tglvat);
                        $DBConnection->add_data("ais_memorial","duedate",$duedate);
                        $DBConnection->add_data("ais_memorial","dk",GetParam("dk999",""));
                        $DBConnection->add_data("ais_memorial","kdact",GetParam("kdact999",""));
                        $DBConnection->add_data("ais_memorial","typevat",GetParam("typevat","010"));
                        $DBConnection->add_data("ais_memorial","vat",GetParam("vat",""));
                        $DBConnection->add_data("ais_memorial","vatrate",$Ratevat);
                        $DBConnection->add_data("ais_memorial","noorder",GetParam("noorder999",""));
                        $DBConnection->add_data("ais_memorial","debtur",GetParam("debtur",""));
                        $DBConnection->add_data("ais_memorial","debnam",GetParam("debnam",""));
                        $DBConnection->add_data("ais_memorial","principal",GetParam("principal",""));
                        $DBConnection->add_data("ais_memorial","principal_code",GetParam("principal_code",""));
                        $DBConnection->add_data("ais_memorial","skada",GetParam("skada999",""));
                        $DBConnection->add_data("ais_memorial","uraian",GetParam("uraian999",""));
                        $DBConnection->add_data("ais_memorial","jumlah",$Jumlah);
                        //$DBConnection->add_data("ais_memorial","rupiah",($Jumlah) * $rate);
						$DBConnection->add_data("ais_memorial","rupiah",$Rupiah);


                        $DBConnection->add_data("ais_memorial","noref",StrToNumber(GetParam("noref1","")));
                        $DBConnection->add_data("ais_memorial","bkn",GetParam("bkn",""));
                        $DBConnection->InsertGrid();


//                        $DBConnection->dbc->debug();

                        SetLogActivity($TransNo,"Update","");
                }
                SaveAging ($TransNo);

                //die();
                header("Location: $FileName?PageMode=Form&nobkt=$TransNo");
                exit;

        }
if (GetParam("FormAction","")=="Delete") {
//                print "Deleted"."<br>\n";
        $SQL = "DELETE FROM  ais_memorial WHERE nobkt='".GetParam("nobkt","")."'";
        $DBConnection->dbc->query($SQL);
        $SQL = "DELETE FROM  ais_piutang WHERE nobkt='".GetParam("nobkt","")."'";
        $DBConnection->dbc->query($SQL);
        $SQL = "DELETE FROM  ais_hutang WHERE nobkt='".GetParam("nobkt","")."'";
        $DBConnection->dbc->query($SQL);
        SetLogActivity($TransNo,"Delete","");
                header("Location: $FileName?PageMode=Form");
                exit;
        }
} else if ((GetParam("Action","")=="CreateFaktur") && GetParam($PRIMARY_KEY,"")) {
        CreateNPWP(GetParam(PRIMARY_KEY,""));
}

//Field Verification
$Verification  = "False";
$SessionVar    = md5(microtime());
//$SessionVar    = "Stuck";
$VerifyFields = array(
                                          "nobkt"=>"ID No.",
                                          "tglbkt"=>"Transaction Date",
					  "typevat"=>"Vat Type",
                                          "tglvat"=>"Vat Date",
                                          "curr"=>"Currency",
                                          "debtur"=>"Billing To",
                                          "location"=>"Location",
                                          "skada1"=>"COA On Line 1",
                                          "uraian999"=>"Uraian On Line 999",
                                          "uraian1"=>"Uraian On Line 1",
                                          "skada999"=>"COA On Line 999");

VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar);


if (GetParam(PRIMARY_KEY,"")) {
        $SQLCount     = "SELECT count(*) FROM `$TableName`";
        $SQLCount    .= "WHERE ".PRIMARY_KEY."='".$PRIMARY_VALUE."' "."AND ".PRIMARY_KEY."='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."' AND urut<>999";;
        $Count        = $DBConnection->dbc->get_var($SQLCount);
} else $Count=0;

$NewDataStart = $Count + 1;
$InitFunction = "Masking();Masking2();";

$VerifyGrids = array("uraian"=>"0","jumlah"=>"number","skada"=>"","dk"=>"");
$Masking1 = BuildMasking ($HTMLFormName,MutatorFields($FormFields,($MaxGrid+$Count)));
$Masking2 = BuildMasking ($HTMLFormName,array("rate"=>"number","tglbkt"=>"date"),"2");
$JSMasks  = $Masking1.$Masking2;
Init($SessionVar,$JSMasks);
FormGridHTML ($HTMLFormName,$VerifyGrids,$Count,$MaxGrid,$SessionVar);



//************ SET FORM MODE ***************
$USER_CANPRINT_TAX="0";
if (GetParam(PRIMARY_KEY,"")) {
        $FormMode = "Edit";
        $USER_CANPRINT="1";
        $SQL ="SELECT vat FROM ais_memorial WHERE nobkt='".GetParam(PRIMARY_KEY,"")."' AND urut=999 ";
        if (strlen($DBConnection->dbc->get_var($SQL))) $USER_CANPRINT_TAX="1";
} else {
        $FormMode = "Add";
        $USER_CANPRINT="0";
}
//******* DATABASE GRID QUERY ***********

$SQL = "SELECT ".BuildFields($FormFields)." FROM `$TableName`";
if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {
    $SQL      = $SQL."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."'";
    $SQL     .= " AND ktrasl='".GetOfficeID()."'";
    $SQLGrid  = $SQL." ORDER BY urut";
}

//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//********************************* HTML Header ******************************************

//Select Currency Table
$SQLCurr = "SELECT * FROM tblcurrency";
//Select Department:
$SQLDept = "SELECT * FROM tbldept";
//Select Receipt:
$SQLReceipt = "SELECT * FROM tblreceipt";
//Select Bank:
$SQLBank = "SELECT * FROM tblbank ORDER BY banknam";
//Select Kantor
$SQLKtr  = "SELECT * FROM tblkantor ORDER BY ktrasl";
//Select Account Actvty
$SQLAct  = "SELECT * FROM tblactivity ORDER BY actname ";
$SQLLocation = "SELECT * FROM $DBCoins.tblsubdepo ORDER BY sdname ";
//$HeaderFields = array("nokwit"=>"0","tglkwit"=>"date","curr"=>"","rate"=>"number","kdbank"=>"0");
$HeaderFields = array("nobkt"=>"","tglbkt"=>"date","tglvat"=>"date","curr"=>"","inc_ppn"=>"","bkn"=>"","rate"=>"number","debtur"=>"","debnam"=>"","principal"=>"","principal_code"=>"","typevat"=>"","vat"=>"","location"=>"");

//Leave Here Untouch
$FormHName     = BuildHTMLField($HeaderFields,"name",1);
$FormHValue    = BuildHTMLField($HeaderFields,"value",1);
$SQLHeader     = "SELECT ".BuildFields($HeaderFields)." FROM $TableName ";

if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") $SQLHeader .= " WHERE ".PRIMARY_KEY."='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."' AND urut=999 ";
$TBS->MergeBlock("currformblk",$DBMysql,$SQLCurr);

$SQL999 = "SELECT * FROM ais_memorial "."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."'";
$SQL999 = $SQL999." AND urut = 999";

$TBS->MergeBlock("dept999blk",$DBMysql,$SQLDept);
if (GetParam(PRIMARY_KEY,"")) {$TBS->MergeBlock("blg9",$DBMysql,$SQL999);}
else $TBS->MergeBlock("blg9",$FormCValue);

// HTML Value
$TBS->MergeBlock("headbln",$FormHName);
$TBS->MergeBlock("dayblk",GetArrayDay());
$TBS->MergeBlock("actblk",$DBMysql,$SQLAct);
$TBS->MergeBlock("actblk9",$DBMysql,$SQLAct);
$TBS->MergeBlock("locblk",$DBMysql,$SQLLocation);

if (GetParam(PRIMARY_KEY,"")) {$TBS->MergeBlock("headblv",$DBMysql,$SQLHeader);}
else $TBS->MergeBlock("headblv",$FormHValue);


//********************************* HTML GRID *********************************************
//HTML Grid
$SQLGrid = "SELECT * FROM ais_memorial "."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."' AND urut<>999 ORDER BY urut";
//print $SQLGrid;
$Result  = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A);
$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);


$TBS->MergeBlock("blg",$Result);
$TBS->Show();

//*************** ACTION FUNCTION *******************

function FormInsert() {
        global $DBConnection,$FileName;
        $DBConnection->Insert();
        header("Location: $FileName?PageMode=Form");
        exit;
}

function FormUpdate() {
        global $DBConnection;
        $DBConnection->Update();
}

function FormDelete() {
        global $DBConnection,$FileName,$TableName;
        $DBConnection->deleteGrid("$TableName","nobkt");
        header("Location: $FileName");
        exit;
}

function FormSearch () {

}

function FormCancel () {
        global $FileName;
        header("Location: ".$FileName."?PageMode=List");
        exit;
}

function FormSave ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey) {
        global $FileName, $MaxGrid, $DBConnection;
        $TotalData = $MaxGrid * 2;
        $NewDataStart = GetParam("NewData","0");
        $NewDataStart = 1;

        for ($a=1;$a<=$TotalData;$a++) {
            if (!GetParam("txtCheck".$a,"")) {
                foreach ($FormFields as $key=>$formatting) {
                        if (!GetParam($keyField.$a,"")) {
                                print GetParam($keyField.$a,"");
                                $EndOfData = 1;
                                break;
                        }
                        $value = GetParam($key.$a,"");
                        if ($formatting=="number") $value = str_replace(",","",$value);
                        if ($formatting=="date") {
                                list($day,$month,$year) = explode("/",$value);
                                $value = "$year-$month-$day";
                    }
                        $DBConnection->add_data($table,$key,$value);
                }

                $rate = StrToNumber(GetParam("rate",""));
                $jmh  = StrToNumber(GetParam("jumlah".$a,""));
                $rupiah = $rate * $jmh;
                $DBConnection->add_data($table,"rupiah",$rupiah);
                if ($EndOfData) {
                        break;
            }
                if (strlen($SpecialCase)) {
                        foreach ($SpecialCase as $key => $value) {
                        //        print "add_data($table,$key,$value);<br>";
                                $DBConnection->add_data($table,$key,$value);
                        }
                }
//                print "$a < $NewDataStart<br>";
                if ($a < $NewDataStart) {
                         if (strlen($PrimaryKey)) {
                            $DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
                          } else {
                            $DBConnection->UpdateGrid($keyField,GetParam($keyField.$a,""));
                     }
                } else {
                        $DBConnection->InsertGrid();
//                        $DBConnection->dbc->debug();
            }
            }
        }
        $DBConnection->ClearData();
}

//*************** USER FUNCTION *******************
function buildsqlfield ($table, $arrayfield) {
                global $DBConnection;
                for ($x=0;$x<count($arrayfield);$x++) {
                        $DBConnection->add_htmlfield($table,$arrayfield[$x],GetParam($arrayfield[$x],""));
                }
}

function DeleteRecord ($sequence_name,$PageSize) {
        global $DBConnection,$FileName,$TableName;
        for ($x=1;$x<=$PageSize;$x++) {
                if (GetParam($sequence_name.$x,""))        {
                        $DBConnection->deleteGrid("$TableName","memorial_id",$sequence_name.$x);
            }
        }
}

function BuildFields ($FormFields) {
                global $DBConnection;
                $str = "";
                foreach ($FormFields as $key=>$formatting) {
                        if (strlen($str)) $str .= ",$key";
                        else $str = "$key";
                }
                return $str;
}

function MutatorFields ($FormFields, $MaxGrid) {
                global $DBConnection;
                $array_fields = array();
                for ($x=0;$x<$MaxGrid;$x++) {
                        foreach ($FormFields as $key=>$formatting){
                                $a=$x+1;
                                $array_fields[$key.$a] = "$formatting";
                        }
                }
                return $array_fields;
}

function FlushCustomer ($TableName, $tmp) {
        global $DBConnection;

        if ($tmp) $TEMPORARY = "TEMPORARY";
        $DBC = new mydb(DB_USER, DB_PASSWORD, DB_NAME2, DB_HOST);

        $SQL = "SELECT kodecustomer,nama,cr_term,kdtype FROM customer ";
        if (GetParam("kdtype","")) $SQL .= " WHERE kdtype='".GetParam("kdtype","")."'";
        $MyResult = $DBC->dbc->get_results($SQL,ARRAY_N);
        if (!$MyResult) return false;
         $session_file = substr(md5(time()), 0, 8);
           $session_file = "/tmp/".$session_file.".tmp";
        BufferToFile ($MyResult,$session_file);

        $DBConnection = new mydb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
        $SQL = "DROP TABLE IF EXISTS `$TableName`;";
        $DBConnection->dbc->query($SQL);

        $SQL= "CREATE $TEMPORARY TABLE `$TableName` (
                          `kodecustomer` varchar(20) NOT NULL default '',
                          `nama` varchar(50) default NULL,
                          `cr_term` int(4) default NULL,
                          `kdtype` varchar(20) default NULL
                          )";
        $DBConnection->dbc->query($SQL);

           $SQL = "LOAD DATA INFILE '$session_file' INTO TABLE $TableName FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'";
        $DBConnection->dbc->query($SQL);
        unlink($session_file);
        return true;
}

function GetLastDateReport() {
        global $DBConnection;
        list($day,$month,$year) = explode("/",GetParam("tglbkt",""));
        $current_date = "$year-$month-$day";

    $SQL = "DELETE FROM ais_piutang_sisa WHERE aging_date>='$current_date' ";
    if (GetParam("curr","")) $SQL .= " AND curr='".GetParam("curr","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND fromskada = '".GetParam("skada999","")."' ";
    if (GetParam("skada999","")) $SQL .= " AND toskada = '".GetParam("skada999","")."' ";
    $DBConnection->dbc->query($SQL);
    //$DBConnection->dbc->debug();

        $SQL = "SELECT max(aging_date) FROM ais_piutang_sisa WHERE aging_date<='$current_date' ";
        if (GetParam("curr","")) $SQL .= " AND curr='".GetParam("curr","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND fromskada = '".GetParam("skada999","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND toskada = '".GetParam("skada999","")."' ";

        return $DBConnection->dbc->get_var($SQL);
}

function CreateNPWP($nokwit) {
        global $DBConnection,$DBGeneral,$DBName,$DBProcess;
        $SQL = "SELECT skada,tglbkt,ktrasl FROM ais_memorial WHERE nobkt='$nokwit' AND skada='".GetPPNSkada()."' ";
        $row = $DBConnection->dbc->get_row($SQL);
	$ktrasl = $row->ktrasl;

        if (!strlen($row->skada)) return;

        $FDate = explode("-",$row->tglbkt);
        $Year  = substr($FDate[0], -2);

        $SQL = "SELECT tbldebtur.cunpwp
      		FROM ais_memorial
      		INNER JOIN tbldebtur ON ais_memorial.debtur=tbldebtur.cucode
      		WHERE nobkt='$nokwit'";
        $isNPWP = $DBConnection->dbc->get_var($SQL);

        $SQL = "SELECT taxcode,taxprefix FROM tblprofile ";
        $TaxResult = $DBConnection->dbc->get_row($SQL);

       $SQL = "SELECT typevat
               FROM ais_memorial
               WHERE nobkt='$nokwit' ";

        $TypeTax = $DBConnection->dbc->get_var($SQL);
//print ('typevat'.$TypeTax.'  ');
        if (strlen($isNPWP)) {
                 //       $NumberStr = $TaxResult->taxprefix.".".$TaxResult->taxcode."-".$Year.".";
                 //   $NumberStr =    $TypeTax.".".$TaxResult->taxcode."-".$Year.".";
		//STANDARD
                 $NumberStr =    ".".$TaxResult->taxcode."-".$Year.".";
                if (intval($Year)>=7)
                $SQL = "SELECT vat FROM $DBProcess.view_faktur_no WHERE substr(vat,9,2)='$Year' and vat not like '$ktrasl%' AND tglbkt>='2007-01-01' ORDER BY right(vat,8) DESC LIMIT 1";
                else
                $SQL = "SELECT vat FROM $DBProcess.view_faktur_no WHERE substr(vat,9,2)='$Year' and vat not like '$ktrasl%' AND tglbkt<'2007-01-01' ORDER BY right(vat,8) DESC LIMIT 1";
        } else {
		// SEDERHANA
                $NumberStr = $TaxResult->taxcode."-";
                if (intval($Year)>=7)
                $SQL = "SELECT vat FROM $DBProcess.view_faktur_no WHERE  vat like '$ktrasl%' AND tglbkt>='2007-01-01' ORDER BY right(vat,8) DESC LIMIT 1";
                else
                $SQL = "SELECT vat FROM $DBProcess.view_faktur_no WHERE vat like '$ktrasl%' AND tglbkt<'2007-01-01' ORDER BY right(vat,8) DESC LIMIT 1";
        }
        //die($SQL);
        $LastTransNo = $DBConnection->dbc->get_var($SQL);

        $Urut = substr($LastTransNo, -8);
//print ('urut'.$Urut.'   ');
        $Urut = intval($Urut)+1;
//print ('urut+1'.$Urut.'   ');
        $SQL = "SELECT LPAD('$Urut',8,'0')";

  if ($isNPWP) {


      //die("shit"." ".$LastTransNo."<p> ".$SQL);
/*
    if (ereg("DL",$LastTransNo)) {

        $Urut = substr($LastTransNo, -5);
              $Urut = intval($Urut)+1;
        $SQL = "SELECT LPAD('$Urut',5,'0')";
        $NumberStr = substr($LastTransNo, 0, 10);
    } else {
*/
        $Urut = substr($LastTransNo, -8);
        $Urut = intval($Urut)+1;
        $SQL = "SELECT LPAD('$Urut',8,'0')";
//    }

  } else {

//    if (intval($Year)>=7) {
      $Urut = substr($LastTransNo, -8);
      $Urut = intval($Urut)+1;
      $SQL = "SELECT LPAD('$Urut',8,'0')";
/*
    } else {

      $Urut = substr($LastTransNo, -5);
      $Urut = intval($Urut)+1;
      $SQL = "SELECT LPAD('$Urut',5,'0')";
      $NumberStr = substr($LastTransNo, 0, 4);
    }
*/
  }

        $Urut = $DBConnection->dbc->get_var($SQL);
        if (strlen($isNPWP)) {
        $NumberStr =  $TypeTax.".".$TaxResult->taxcode."-".$Year.".".$Urut;
        }else{
        $NumberStr = $NumberStr.$Urut;
        }
        //die($NumberStr);


        $SQL = "UPDATE ais_memorial SET vat='$NumberStr' WHERE nobkt='$nokwit' ";
        $DBConnection->dbc->query($SQL);
}

function CreateVoucher($nobkt) {
        global $DBConnection,$DBGeneral,$DBName, $DBProcess;

        $SQL = "SELECT skada FROM ais_memorial WHERE nobkt='$nobkt' AND skada='".GetPPNSkada()."' ";
        if (!strlen($DBConnection->dbc->get_var($SQL))) return;

        $SQL = "SELECT CUNPWP
                        FROM ais_memorial
                        LEFT JOIN $DBName.tbldebtur ON ais_memorial.debtur=$DBName.tbldebtur.cucode
                        WHERE nobkt='$nobkt' ";

//        $SQL = "SELECT npwp FROM ais_receipt WHERE nokwit='$nokwit' ";
        $isNPWP = $DBConnection->dbc->get_var($SQL);

          $SQL = "SELECT typevat
                        FROM ais_memorial
                        WHERE nobkt='$nobkt' ";
        $TypeTax = $DBConnection->dbc->get_var($SQL);
         //die( $TypeTax);

        $SQL = "SELECT taxcode,taxprefix FROM tblprofile ";
        $TaxResult = $DBConnection->dbc->get_row($SQL);

        if (strlen($isNPWP)) {
                $NumberStr = $TypeTax."-".$TaxResult->taxcode."-";
        } else {
                $NumberStr = $TaxResult->taxcode."-";
        }

/*
        $SQL = "
                        CREATE VIEW tblvat AS
                        SELECT nobkt,vat FROM ais_memorial WHERE ifnull(vat,'')<>''
                        UNION
                        SELECT nokwit as nobkt,faktur as vat FROM ais_receipt WHERE ifnull(faktur,'')<>''
                        ";
*/

        $LastTransNo = $DBConnection->dbc->query($SQL);
        $SQL = "SELECT vat FROM $DBProcess.view_faktur_no WHERE vat like '$NumberStr%' ORDER BY vat DESC LIMIT 1";
        $LastTransNo = $DBConnection->dbc->get_var($SQL);

        $Urut = substr($LastTransNo, -8);
        $Urut = intval($Urut)+1;
        $SQL = "SELECT LPAD('$Urut',8,'0')";
        $Urut = $DBConnection->dbc->get_var($SQL);
        $NumberStr = $NumberStr.$Urut;

        $SQL = "UPDATE ais_memorial SET vat='$NumberStr' WHERE nobkt='$nobkt' ";
        $DBConnection->dbc->query($SQL);
}

?>
